    //
//  athemPlayer.m
//  _2010WorldCupNationalAthem
//
//  Created by Apple on 2010/7/13.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "athemPlayer.h"
#import <AVFoundation/AVFoundation.h>

@implementation athemPlayer

@synthesize countryNameToPlay ;
@synthesize countryNameToShow ;


@synthesize countryImage ;
@synthesize playPauseButton ;


#ifdef FOR_IOS4_ONLY
@synthesize bannerIsVisible ;
@synthesize adView ;
#endif

//**********************************************************
// method of AVAudioPlayerDelegate protocol
//	music播完後會call this method
//**********************************************************

- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer*)player successfully:(BOOL)flag
{
	[playPauseButton setTitle:@"PLAY AGAIN" forState:UIControlStateHighlighted] ;
	[playPauseButton setTitle:@"PLAY AGAIN" forState:UIControlStateNormal] ;

	[UIApplication sharedApplication].idleTimerDisabled=NO;

	play_flag = 0 ;
}



//**********************************************************
// method of ADBannerViewDelegate protocol
//	
//**********************************************************
#ifdef FOR_IOS4_ONLY

- (void)bannerViewDidLoadAd:(ADBannerView *)banner
{
	if (!self.bannerIsVisible)
	{
		[UIView beginAnimations:@"animateAdBannerOn" context:NULL];

		[UIView commitAnimations];
		self.bannerIsVisible = YES;
	}
}



//**********************************************************
// method of ADBannerViewDelegate protocol
//	==> iAD start playing
//**********************************************************

- (BOOL)bannerViewActionShouldBegin:(ADBannerView *)banner willLeaveApplication:(BOOL)willLeave 
{
	// stop the music	
	//
	[player stop] ;
	play_flag = 0 ;
	[UIApplication sharedApplication].idleTimerDisabled=NO;


	
    return YES;
}


//**********************************************************
// method of ADBannerViewDelegate protocol
//	==> iAD stop playing
//**********************************************************

- (void)bannerViewActionDidFinish:(ADBannerView *)banner 
{
    NSLog(@"[iAd]: Action finished.");
	
	// re-start music playing
	[player play] ;
	[UIApplication sharedApplication].idleTimerDisabled=YES;

    
	[playPauseButton setTitle:@"PAUSE" forState:UIControlStateNormal] ;
	[playPauseButton setTitle:@"PAUSE" forState:UIControlStateHighlighted] ;
	
	play_flag = 1 ;
	
}

#endif


//**********************************************************
// method of ADBannerViewDelegate protocol
//	
//**********************************************************
#ifdef FOR_IOS4_ONLY

- (void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
	if (self.bannerIsVisible)
	{
		[UIView beginAnimations:@"animateAdBannerOff" context:NULL];
		
		// banner is visible and we move it out of the screen, due to connection issue
		//banner.frame = CGRectOffset(banner.frame, 0, -50);

		[UIView commitAnimations];
		self.bannerIsVisible = NO;
	}
}
#endif

//**********************************************************
// Privtate method:  playOrPause
// switch PLAY/PAUSE status
//
//**********************************************************
-(IBAction)playOrPause:(id)sender
{
	
		if(play_flag == 1) // playing
		{
			[playPauseButton setTitle:@"RESUME" forState:UIControlStateHighlighted] ;
			[playPauseButton setTitle:@"RESUME" forState:UIControlStateNormal] ;
			play_flag = 0 ;

			// pause the mousic
			[player pause] ;
			[UIApplication sharedApplication].idleTimerDisabled=NO;

			
			/* 
			 // 這裡出現一個alert box似乎會嚇到使用者
			 //
			if(alertCounter == 0)
			{
				UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Press this button to resume music." 
															 message:@"Please back to country-list and select the country again if you want to restart playing." 
															delegate:nil 
												   cancelButtonTitle:@"OK" 
												   otherButtonTitles:nil ] ;
			
				[alert show] ;
				[alert release] ;
				
				alertCounter = 1 ;
			}
			*/
		}
		else 
		{
			// resume the music
			[player play] ;
			[playPauseButton setTitle:@"PAUSE" forState:UIControlStateNormal] ;
			[playPauseButton setTitle:@"PAUSE" forState:UIControlStateHighlighted] ;
			
			play_flag = 1 ;
			[UIApplication sharedApplication].idleTimerDisabled=YES;

		}

	
	
}


//**********************************************************
// Privtate method:  setCountryName
// 跳到播放畫面，傳入國家名稱
//
//**********************************************************

- (void) setCountryName:(NSString *)name1 nameToShow:(NSString *)name2 
{
	self.countryNameToPlay = name1 ; 
	self.countryNameToShow = name2 ;
}



//**********************************************************
// Org. method:  viewDidLoad
//
//**********************************************************

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad 
{
	CGRect rect = CGRectMake(0, 0, 200, 44);
	UILabel * nav_bar_title ;
	
	NSString * nvbar_str ;

	NSString * imageName ;
	NSString * audioName ;
	
	// show naviation bar
	//
	nav_bar_title = [[UILabel alloc] initWithFrame:rect];
    nav_bar_title.backgroundColor = [UIColor clearColor];
	
	nvbar_str = [[NSString alloc] initWithFormat:@"Anthem of %@",self.countryNameToShow] ;
	
    nav_bar_title.text = nvbar_str ;    
    self.navigationItem.titleView = nav_bar_title;

	[nav_bar_title release] ;

	
	// copy-code start : show a image ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//
	// show image file (filename)
	//
	imageName = [[NSString alloc] initWithFormat:@"%@-match.JPG",self.countryNameToPlay] ;

	[countryImage setImage:[UIImage imageNamed:imageName]];
	countryImage.opaque = YES; // explicitly opaque for performance
	[self.view addSubview:countryImage];	
	
	//設定圖片的透明度 值為0.0~1.0(圖片隱藏～完全不隱藏)
	//[countryImage setAlpha:0.8];	
	
	//
	// copy-code end  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~	
		
	[imageName release] ;
	
#ifdef FOR_IOS4_ONLY	
	// copy-code start ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//
	// show iAD banner
	//	
	//	已經用ib建立關係，所以無需重新alloc
	self.adView = [[ADBannerView alloc] initWithFrame:CGRectMake(0, 368, 320, 50)/*CGRectZero*/];
	self.adView.backgroundColor = [UIColor whiteColor];
	
	// set location of iAD banner to bottom
	//
	
	self.adView.requiredContentSizeIdentifiers = [NSSet setWithObject:ADBannerContentSizeIdentifier320x50];
	self.adView.currentContentSizeIdentifier = ADBannerContentSizeIdentifier320x50;
	[self.view addSubview:adView];	
	
	self.adView.delegate=self;
	self.bannerIsVisible=NO;

	//
	// copy-code end ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#endif
	
#ifdef FREE_VERSION
		
	// start playing
	//
	audioName = [[NSString alloc] initWithFormat:@"%@-instrumental",self.countryNameToPlay] ;
	
#else
	audioName = [[NSString alloc] initWithFormat:@"%@-vocal",self.countryNameToPlay] ;
	
#endif
	// An NSBundle object represents a location in the file system 
	// that groups code and resources that can be used in a program.
	// NSBundle objects locate program resources,
	NSBundle* bundle = [NSBundle mainBundle] ;
	
	NSString* path = [bundle pathForResource:audioName ofType:@"mp3"] ;
	NSURL * url = [NSURL fileURLWithPath:path] ;
	
	player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil] ;
	player.volume = 1.0f ;

	[player setDelegate:self]; // Notify Delegate for audioPlayerDidFinishPlaying
	[player prepareToPlay];	
	
	BOOL result = [player play] ;	// this method also works on emulator!
	
	if(result == YES)
		play_flag = 1 ;
	else 
	{
		// copy-code start  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		//
		// show an alert message box
		
		UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Sorry! Cannot Play!" 
														 message:@"Please restart the APP" 
														 delegate:nil 
														 cancelButtonTitle:@"OK" 
														 otherButtonTitles:nil ] ;
		
		[alert show] ;
		[alert release] ;
	
		// copy-code end  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
	}
	
	[UIApplication sharedApplication].idleTimerDisabled=YES;//not let iphone go to sleep


	
	[audioName release] ;

	
	[super viewDidLoad];
}



/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/


/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload 
{
	self.countryNameToPlay = nil ;
	self.countryNameToShow = nil ;
	self.countryImage = nil ;
	self.playPauseButton = nil ;
	
#ifdef FOR_IOS4_ONLY	
	self.adView = nil ;
#endif
	
    [super viewDidUnload];
	
	[UIApplication sharedApplication].idleTimerDisabled=NO;

    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc 
{

	[countryNameToPlay release] ;
	[countryNameToShow release] ;
	[countryImage release] ;
	[playPauseButton release] ;

	[player release] ;
	[UIApplication sharedApplication].idleTimerDisabled=NO;

	
#ifdef FOR_IOS4_ONLY
	[adView release] ;
#endif    
	[super dealloc];
}


@end
